package com.spring.dynamicdatasource.config;

import com.spring.dynamicdatasource.enums.DatabaseType;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * 一些配置信息
 *
 * @author HouKunLin
 * @date 2019/9/10 0010 10:34
 */
@Configuration
public class FreemarkerConfig implements ApplicationListener<ContextRefreshedEvent>, InitializingBean {

    @Autowired
    private freemarker.template.Configuration configuration;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    }

    /**
     * 初始化FreeMarker框架的字符串渲染加载器（新增一个字符串模板加载器）
     */
    public void initFreemarkerTemplateLoader() {
        MultiTemplateLoader templateLoader = (MultiTemplateLoader) configuration.getTemplateLoader();
        int len = templateLoader.getTemplateLoaderCount();
        TemplateLoader[] arr = new TemplateLoader[len + 1];
        for (int i = 0; i < len; i++) {
            arr[i] = templateLoader.getTemplateLoader(i);
        }
        arr[len] = stringTemplateLoader();

        configuration.setTemplateLoader(new MultiTemplateLoader(arr));
    }

    /**
     * 创建字符串模板加载器
     *
     * @return 字符串模板加载器
     */
    public StringTemplateLoader stringTemplateLoader() {
        StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
        for (DatabaseType value : DatabaseType.values()) {
            stringTemplateLoader.putTemplate(value.getKey(), value.getJdbcUrl());
        }
        return stringTemplateLoader;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initFreemarkerTemplateLoader();
    }
}
